<script setup lang="ts">
import dayjs from 'dayjs'
import {
  generateInviteUsingGet,
  inviteUserUsingPost,
  listTeamUserHistoryUsingPost,
  pageUserInTeamUsingPost
} from '@/api/teamController'
import { useTeamStore, useUserStore } from '@/store'
import { onMounted, ref, Ref, computed, watch } from 'vue'
import {
  Table,
  TableColumn,
  Input,
  Select,
  Button,
  Avatar,
  Tag,
  Space,
  Modal,
  Message,
  Form,
  FormItem,
  Tooltip,
  Textarea
} from '@arco-design/web-vue'
import { TeamRole, TeamRoleName, getTeamRoleInfo } from '@/constants/teamRole'
import {
  addUserUsingPost,
  deleteUserUsingDelete,
  listUserByPageUsingPost,
  updateUserUsingPut
} from '@/api/userController'
import { debounce } from 'lodash'
import { kickOutUsingPost } from '@/api/teamController'
import { updateTeamUsingPut } from '@/api/teamController'

const userStore = useUserStore()
const teamStore = useTeamStore()

// 搜索条件
const searchForm = ref({
  name: '',
  email: '',
  phone: '',
  role: -1
})

// 角色选项
const roleOptions = [
  { label: '全部', value: -1 },
  { label: TeamRoleName[TeamRole.MEMBER], value: TeamRole.MEMBER },
  { label: TeamRoleName[TeamRole.ADMIN], value: TeamRole.ADMIN }
]

// 请求参数
const userInTeamRequest: Ref<API.UserInTeamRequest> = ref({
  current: 1,
  pageSize: 1000,
  teamId: teamStore.selectedTeam?.id,
  name: '',
  email: '',
  phone: '',
  role: -1
})

const formData: Ref<API.UserInTeamVo[]> = ref([])

// 获取角色信息
const getRoleInfo = (record: API.UserInTeamVo) => {
  return getTeamRoleInfo(
    record?.role ?? TeamRole.MEMBER,
    record.id === teamStore.selectedTeam?.ownerId
  )
}

// 获取标签颜色
const getTagColor = (tag: string, index: number) => {
  const colors = ['blue', 'green', 'orange', 'purple', 'magenta']
  return colors[index % colors.length]
}

// 加载数据
const loadTeamUserList = async () => {
  if (!teamStore.selectedTeam?.id) return
  const res: any = await pageUserInTeamUsingPost(userInTeamRequest.value)
  formData.value = res.data.records
}

// 搜索方法
const handleSearch = async () => {
  userInTeamRequest.value = {
    ...userInTeamRequest.value,
    name: searchForm.value.name,
    email: searchForm.value.email,
    phone: searchForm.value.phone,
    role: searchForm.value.role ?? -1
  }
  await loadTeamUserList()
}

// 重置方法
const handleReset = async () => {
  searchForm.value = {
    name: '',
    email: '',
    phone: '',
    role: -1
  }
  await handleSearch()
}

// 编辑弹窗控制
const editVisible = ref(false)
const editingUser = ref<API.UserInTeamVo | null>(null)

// 编辑用户表单
const editUserForm = ref({
  nickname: '',
  password: ''
})

// 编辑用户表单验证规则
const editUserRules = {
  nickname: [
    { minLength: 1, message: '昵称至少1个字符' },
    { maxLength: 32, message: '昵称最多32个字符' }
  ],
  password: [
    { minLength: 8, message: '密码至少8个字符' },
    { maxLength: 32, message: '密码最多32个字符' }
  ]
}

// 添加表单引用
const editUserFormRef = ref()

// 修改编辑处理方法
const handleEdit = (record: API.UserInTeamVo) => {
  editingUser.value = record
  // 填充表单数据
  editUserForm.value.nickname = record.nickname || ''
  editUserForm.value.password = '' // 密码不填充
  editVisible.value = true
}

// 修改处理编辑提交的函数
const handleEditSubmit = async () => {
  if (!editUserFormRef.value) {
    return
  }
  try {
    // 表单验证
    const errorValid = await editUserFormRef.value?.validate()
    if (errorValid) {
      return
    }

    // 添加参数校验
    if (!editUserForm.value.nickname && !editUserForm.value.password) {
      editVisible.value = false
      return
    }

    // 构建更新请求参数
    const updateParams = {
      id: editingUser.value?.id, // 添加用户ID
      nickname: editUserForm.value.nickname || undefined, // 如果为空则不更新
      password: editUserForm.value.password || undefined  // 如果为空则不更新
    }

    // 调用修改用户接口
    const res: any = await updateUserUsingPut(updateParams)
    if (res.code === 0) {
      Message.success('修改成功')
      await loadTeamUserList() // 重新加载列表
    } else {
      Message.error(res.message || '修改失败')
    }
  } catch (error) {
    console.error('修改用户失败:', error)
    Message.error('修改失败')
  } finally {
    editVisible.value = false
    // 重置表单
    editUserForm.value = {
      nickname: '',
      password: ''
    }
    // 清除编辑状态
    editingUser.value = null
  }
}

// 修改处理编辑弹窗关闭方法
const handleEditCancel = () => {
  editVisible.value = false
  editingUser.value = null
  // 重置表单
  editUserForm.value = {
    nickname: '',
    password: ''
  }
  // 清除表单验证状态
  editUserFormRef.value?.resetFields()
}

// 修改踢出处理方法
const teamKickOutRequest: Ref<API.TeamKickOutRequest> = ref({})
const handleKick = (record: API.UserInTeamVo) => {
  Modal.warning({
    title: '移除确认',
    content: `是否移除该成员 "${record.name}"？`,
    modalClass: 'warning-modal',
    alignCenter: true,
    okText: '确定移除',
    cancelText: '取消',
    hideCancel: false,
    okButtonProps: {
      status: 'warning' // 使用警告色
    },
    onOk: async () => {
      //  调用移除成员接口
      try {
        teamKickOutRequest.value.userId = record.id
        teamKickOutRequest.value.teamId = teamStore.selectedTeam?.id
        const res: any = await kickOutUsingPost(teamKickOutRequest.value)
        if (res.code === 0) {
          Message.success('移除成功')
        } else {
          Message.error(res.message || '操作失败')
        }
      } catch (e) {
      } finally {
        // 重新加载列表
        loadTeamUserList()
      }
    },
    onCancel: () => {
      Message.info('已取消移除')
    }
  })
}

const deleteRequest: Ref<API.DeleteRequest> = ref({})
const handleDelete = (record: API.UserInTeamVo) => {
  Modal.warning({
    title: '删除确认',
    content: `确定要删除用户 "${record.name}" 吗？`,
    modalClass: 'warning-modal',
    alignCenter: true, // 内容居中
    okText: '确定删除',
    cancelText: '取消',
    hideCancel: false, // 显示取消按钮
    okButtonProps: {
      status: 'danger'
    },
    onOk: async () => {
      try {
        deleteRequest.value.id = record?.id
        deleteRequest.value.teamId = teamStore.selectedTeam?.id
        const res: any = await deleteUserUsingDelete(deleteRequest.value)
        if (res.code === 0) {
          Message.success('删除成功')
        } else {
          Message.error(res.message || '操作失败')
        }
      } catch (e) {
        console.error('删除用户失败:', e)
      } finally {
        // 重新加载列表
        loadTeamUserList()
      }
    },
    onCancel: () => {}
  })
}

// 添加弹窗控制变量
const inviteVisible = ref(false)

// 修改邀请弹窗打开方法
const handleInvite = async () => {
  inviteVisible.value = true
  // 加载团队成员变动记录
  await loadTeamMemberChangeLogs()
}

// 添加分页相关变量
const currentPage = ref(1)
const hasMore = ref(true)

// 修改类型定义
interface UserOption {
  label: string
  value: string
  username: string
  disabled?: boolean
  avatar?: string
  nickname?: string
  isInTeam?: boolean
  isPending?: boolean // 添加待确认状态
}

// 修改变量定义，存储完整的用户信息
const selectedUsers = ref<UserOption[]>([])

// 加载状态
const loading = ref(false)

// 是否下拉框关闭
const isDropdownClosed = ref(true)

// 搜索查询值
const userQueryRequest = ref({
  current: 1,
  pageSize: 10,
  username: ''
})

// 添加一个新的 ref 来存储选中的用户 ID
const selectedUserIds = ref<string[]>([])

// 修改 Select 组件的绑定
const handleSelectionChange = (values: string[]) => {
  // 更新选中的用户 ID
  selectedUserIds.value = values

  // 根据选中的 ID 找到对应的完整用户信息
  const selectedUserInfos = values
    .map((value) => filteredUsers.value.find((user) => user.value === value))
    .filter((user): user is UserOption => user !== undefined)

  if (selectedUserInfos.length > 5) {
    selectedUsers.value = selectedUserInfos.slice(0, 5)
    selectedUserIds.value = selectedUserIds.value.slice(0, 5)
  } else {
    selectedUsers.value = selectedUserInfos
  }
}

// 修改移除用户的方法
const handleRemoveUser = (userId: string) => {
  selectedUsers.value = selectedUsers.value.filter((user) => user.value !== userId)
  selectedUserIds.value = selectedUserIds.value.filter((id) => id !== userId)
}

// 修改 handleReachBottom 方法
const handleReachBottom = async () => {
  // 如果没有更多数据，或正在加载，或没有搜索关键词，直接返回
  if (!hasMore.value || loading.value || !userQueryRequest.value.username) {
    console.log('No more data to load or loading in progress')
    return
  }

  // 计算当前应该加载的页数
  const shouldLoadPage = Math.ceil(filteredUsers.value.length / userQueryRequest.value.pageSize) + 1

  // 如果当前页已经加载过，不再重复加载
  if (shouldLoadPage !== userQueryRequest.value.current + 1) {
    console.log('This page has already been loaded')
    return
  }

  loading.value = true
  try {
    const nextPage = userQueryRequest.value.current + 1
    console.log('Loading page:', nextPage)

    const res: any = await listUserByPageUsingPost({
      ...userQueryRequest.value,
      current: nextPage
    })

    if (res?.data?.records) {
      const newUsers = res.data.records
        .filter((user: API.UserVO) => user.id !== userStore.user?.id)
        .map((user: API.UserVO) => ({
          label: user.username || '',
          value: user.id?.toString() || '',
          username: user.username || '',
          disabled:
            formData.value.some((teamUser) => teamUser.id === user.id) ||
            teamUserHistoryVoList.value.some(
              (record) => record.status === 1 && record.invitedId === user.id
            ),
          avatar: user.avatar,
          nickname: user.nickname,
          isInTeam: formData.value.some((teamUser) => teamUser.id === user.id),
          isPending: teamUserHistoryVoList.value.some(
            (record) => record.status === 1 && record.invitedId === user.id
          )
        }))

      // 添加新的用户到列表中
      filteredUsers.value = [...filteredUsers.value, ...newUsers]

      const total = res.data.total || 0
      const currentCount = filteredUsers.value.length

      // 只有在还有更多数据时才更新页码
      if (currentCount < total) {
        userQueryRequest.value.current = nextPage
        hasMore.value = true
      } else {
        hasMore.value = false
      }

      console.log('Load more results:', {
        total,
        currentCount,
        hasMore: hasMore.value,
        currentPage: userQueryRequest.value.current,
        shouldLoadPage
      })
    } else {
      hasMore.value = false
    }
  } catch (error) {
    console.error('Load more error:', error)
    Message.error('加载更多失败')
    hasMore.value = false
  } finally {
    loading.value = false
  }
}

// 在其他变量定义之后，添加 filteredUsers 的定义
const filteredUsers = ref<UserOption[]>([])

// 修改计算属性
const getFilteredUsers = computed(() => {
  const users = filteredUsers.value.map((user) => ({
    ...user,
    isInTeam: formData.value.some((teamUser) => teamUser.id === Number(user.value)),
    isPending: teamUserHistoryVoList.value.some(
      (record) => record.status === 1 && record.invitedId === Number(user.value)
    ),
    disabled:
      formData.value.some((teamUser) => teamUser.id === Number(user.value)) || // 已在团队中
      teamUserHistoryVoList.value.some(
        (record) => record.status === 1 && record.invitedId === Number(user.value)
      ) || // 有待确认邀请
      (selectedUserIds.value.length >= 5 && !selectedUserIds.value.includes(user.value)) // 选择数量限制
  }))

  if (hasMore.value) {
    users.push({
      label: loading.value ? '加载中...' : '向下滚动加载更多',
      value: '__loading__',
      disabled: true,
      username: '',
      isInTeam: false,
      isPending: false
    })
  }

  return users
})

// 添加空状态文本的计算属性
const emptyText = computed(() => {
  if (loading.value) return '搜索中...'
  if (!userQueryRequest.value.username) return '请输入用户名搜索'
  return '暂无匹配数据'
})

// 添加处理搜索的方法
const handleSearchUser = (query: string) => {
  userQueryRequest.value = {
    current: 1,
    pageSize: 10,
    username: query.trim()
  }
  debouncedSearch(query)
}

// 添加处理焦点的方法
const handleFocus = () => {
  if (isDropdownClosed.value) {
    filteredUsers.value = []
  }
  isDropdownClosed.value = false
}

// 添加处理下拉框可见性变化的方法
const handleDropdownVisibleChange = (visible: boolean) => {
  if (!visible) {
    isDropdownClosed.value = true
    filteredUsers.value = []
    userQueryRequest.value.current = 1
    hasMore.value = true
    userQueryRequest.value.username = ''
  }
}

// 修改处理邀请的方法
const handleInviteUsers = () => {
  Modal.confirm({
    title: '邀请确认',
    content: `是否邀请用户：${selectedUsers.value.map((user) => user.label).join('、')}？`,
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      try {
        // 打印将要邀请的用户信息
        console.log('Inviting users:', {
          selectedUsers: selectedUsers.value,
          selectedUserIds: selectedUserIds.value,
          teamId: teamStore.selectedTeam?.id
        })

        // TODO: 实现邀请逻辑
        const res: any = await inviteUserUsingPost({
          teamId: teamStore.selectedTeam?.id,
          userIds: selectedUserIds.value.map((id) => Number(id))
        })
        if (res.code === 0) {
          Message.success('邀请成功')
          inviteVisible.value = false
          selectedUsers.value = []
          selectedUserIds.value = []
        } else {
          Message.error(res.message || '邀请失败')
        }
      } catch (error) {
        console.error('Invite error:', error)
        Message.error('邀请失败')
      }
    }
  })
}

// 修改 debouncedSearch 方法
const debouncedSearch = debounce(async (query: string) => {
  if (!query.trim()) {
    filteredUsers.value = []
    loading.value = false
    return
  }

  loading.value = true
  try {
    const res: any = await listUserByPageUsingPost({
      ...userQueryRequest.value,
      username: query.trim(),
      pageSize: 10
    })

    if (res?.data?.records) {
      // 重置当前页为1
      userQueryRequest.value.current = 1

      filteredUsers.value = res.data.records
        .filter((user: API.UserVO) => user.id !== userStore.user?.id)
        .map((user: API.UserVO) => ({
          label: user.username || '',
          value: user.id?.toString() || '',
          username: user.username || '',
          disabled:
            formData.value.some((teamUser) => teamUser.id === user.id) ||
            teamUserHistoryVoList.value.some(
              (record) => record.status === 1 && record.invitedId === user.id
            ),
          avatar: user.avatar,
          nickname: user.nickname,
          isInTeam: formData.value.some((teamUser) => teamUser.id === user.id),
          isPending: teamUserHistoryVoList.value.some(
            (record) => record.status === 1 && record.invitedId === user.id
          )
        }))

      // 修改 hasMore 的判断逻辑
      const total = res.data.total || 0
      const currentCount = filteredUsers.value.length

      // 判断是否已加载所有数据
      hasMore.value = currentCount < total

      console.log('Search results:', {
        total,
        currentCount,
        hasMore: hasMore.value,
        currentPage: userQueryRequest.value.current
      })
    } else {
      filteredUsers.value = []
      hasMore.value = false
    }
  } catch (error) {
    console.error('Search error:', error)
    Message.error('搜索失败')
    filteredUsers.value = []
    hasMore.value = false
  } finally {
    loading.value = false
  }
}, 500)

//团队变动历史表
const teamUserHistoryVoList: Ref<API.TeamUserHistoryVo[]> = ref([])

const teamUserHistoryPageRequest: Ref<API.TeamUserHistoryVo> = ref({
  current: 1,
  pageSize: 1000,
  teamId: teamStore.selectedTeam?.id
})
// 添加团队成员变动记录查询
const loadTeamMemberChangeLogs = async () => {
  const res: any = await listTeamUserHistoryUsingPost(teamUserHistoryPageRequest.value)
  teamUserHistoryVoList.value = res.data.records
  console.log(teamUserHistoryVoList.value)
}

// 添加判断是否可以编辑的方法
const canEdit = (record: API.TeamUserVo) => {
  return (
    userStore.user.id === teamStore.selectedTeam?.ownerId && // 是团队拥有者
    record.createBy === userStore.user.id && // 是记录创建者
    record.id !== userStore.user.id // 不是自己
  )
}

// 添加判断是否可以删除的方法
const canDelete = (record: API.TeamUserVo) => {
  return (
    teamStore.selectedTeam?.ownerId === userStore.user.id && // 是团队拥有者
    record.createBy === userStore.user.id // 是记录创建者
  )
}

// 添加判断是否可以踢出的方法
const canKick = (record: API.TeamUserVo) => {
  const yes =
    teamStore.selectedTeam?.ownerId === userStore.user.id && // 是团队拥有者
    record.id !== userStore.user.id && // 不是自己
    record.id !== teamStore.selectedTeam?.ownerId // 不是团队拥有者
  return yes
}

// 创建用户弹窗控制
const createUserVisible = ref(false)

// 修改创建用户表单
const createUserForm = ref({
  username: '',
  name: ''
})

// 修改创建用户表单验证规则
const createUserRules = {
  username: [
    { required: true, message: '请输入用户名' },
    { minLength: 8, message: '用户名至少8个字符' },
    { maxLength: 32, message: '用户名最多32个字符' }
  ],
  name: [
    { required: true, message: '请输入姓名' },
    { minLength: 1, message: '姓名至少1个字符' },
    { maxLength: 10, message: '姓名最多10个字符' }
  ]
}

// 处理创建用户提交
const userAddRequest: Ref<API.UserAddRequest> = ref({})
const handleCreateUserSubmit = async () => {
  if (!createUserFormRef.value) {
    return
  }
  const errorValid = await createUserFormRef.value?.validate()
  if (errorValid) {
    return
  }
  try {
    userAddRequest.value.name = createUserForm.value.name
    userAddRequest.value.username = createUserForm.value.username
    userAddRequest.value.teamId = teamStore.selectedTeam?.id
    // TODO: 调用创建用户接口
    const res: any = await addUserUsingPost(userAddRequest.value)
    if (res.code === 0) {
      Message.success('创建成功')
      await loadTeamUserList()
    } else {
      Message.error(res.message || '创建失败')
    }
  } catch (error) {
    console.error('创建用户失败', error)
  } finally {
    createUserVisible.value = false
    // 重置表单
    createUserForm.value = {
      username: '',
      name: ''
    }
  }
}

// 添加表单引用
const createUserFormRef = ref()

// 处理创建用户按钮点击
const handleCreateUser = () => {
  createUserVisible.value = true
}

// 修改处理创建用户弹窗关闭方法
const handleCreateUserCancel = () => {
  createUserVisible.value = false
  // 重置表单
  createUserForm.value = {
    username: '',
    name: ''
  }
  // 清除表单验证状态
  createUserFormRef.value?.resetFields()
}

// 生成链接
const inviteLink = ref('')
const inviteCode = ref('')
const handleGenerateLink = async () => {
  try {
    const res: any = await generateInviteUsingGet({
      teamId: teamStore.selectedTeam?.id
    })
    if (res.code === 0 && res.data) {
      // 解析完整URL，只保留最后的短链接代码
      const url = new URL(res.data)
      const pathParts = url.pathname.split('/')
      inviteLink.value = res.data
      inviteCode.value = pathParts[pathParts.length - 1] // 获取最后一段作为短链接代码
      Message.success('已生成邀请链接')
    } else {
      Message.error(res.message || '生成链接失败')
    }
  } catch (e) {
    Message.error('生成链接失败')
  }
}
// 修改复制链接的方法
const handleCopyLink = async (type: 'code' | 'url') => {
  try {
    const textToCopy = type === 'code' ? inviteCode.value : inviteLink.value
    await navigator.clipboard.writeText(textToCopy)
    Message.success('链接已复制')
  } catch (err) {
    Message.error('复制失败')
  }
}

// 添加计算属性判断是否是团队拥有者
const isTeamOwner = computed(() => {
  return userStore.user?.id === teamStore.selectedTeam?.ownerId
})

// 监听团队变更
watch(
  () => teamStore.selectedTeam,
  async (newTeam) => {
    if (!newTeam?.id) return

    // 更新请求参数中的团队ID
    userInTeamRequest.value.teamId = newTeam.id
    teamUserHistoryPageRequest.value.teamId = newTeam.id

    try {
      // 重新加载所有相关数据
      await Promise.all([
        loadTeamUserList(), // 加载团队成员列表
        loadTeamMemberChangeLogs() // 加载团队成员变动记录
      ])

      // 重置搜索条件
      await handleReset()

      // 重置分页
      currentPage.value = 1

      // 清空选中的用户
      selectedUsers.value = []
      selectedUserIds.value = []

      // 关闭所有打开的弹窗
      inviteVisible.value = false
      createUserVisible.value = false
      editVisible.value = false
    } catch (error) {
      console.error('Failed to update team data:', error)
      Message.error('加载团队数据失败')
    }
  },
  { immediate: true, deep: true }
)

// 添加修改团队信息相关的状态和方法
const editTeamVisible = ref(false)

// 编辑团队表单
const editTeamForm = ref({
  teamId: teamStore.selectedTeam?.id,
  name: '',
  description: '',
  maxMember: 5
})

// 表单验证规则
const editTeamRules = {
  name: [
    { required: true, message: '请输入团队名称' },
    { minLength: 1, message: '团队名称至少1个字符' },
    { maxLength: 32, message: '团队名称最多32个字符' }
  ],
  description: [{ maxLength: 300, message: '团队简介最多300个字符' }],
  maxMember: [
    { required: true, message: '请选择团队人数上限' },
    {
      validator: (value: number) => {
        return value >= formData.value.length
      },
      message: '人数上限不能小于当前团队人数'
    }
  ]
}

// 团队人数选项（动态生成，基于当前团队人数）
const memberLimitOptions = computed(() => {
  const currentMembers = formData.value.length
  const options = [5, 10, 20, 50]
  return options
    .filter((num) => num >= currentMembers)
    .map((num) => ({
      label: `${num}人`,
      value: num
    }))
})

// 打开编辑团队弹窗
const handleEditTeam = () => {
  editTeamForm.value = {
    name: teamStore.selectedTeam?.name || '',
    description: teamStore.selectedTeam?.description || '',
    maxMember: teamStore.selectedTeam?.maxMember || 5
  }
  editTeamVisible.value = true
}

// 处理编辑团队提交
const handleEditTeamSubmit = async () => {
  if (!editTeamFormRef.value) return

  try {
    const errorValid = await editTeamFormRef.value.validate()
    if (errorValid) return
    editTeamForm.value.teamId = teamStore.selectedTeam?.id
    // 调用修改团队信息的接口
    const res: any = await updateTeamUsingPut({
      ...editTeamForm.value
    })
    if (res.code === 0) {
      Message.success('修改成功')
      // 重新获取团队信息
      await teamStore.getTeamUserVo()
    } else {
      Message.error(res.message || '修改失败')
    }
  } catch (error) {
    console.error('修改团队失败:', error)
    Message.error('修改失败')
  } finally {
    editTeamVisible.value = false
  }
}

// 添加表单引用
const editTeamFormRef = ref()

// 添加一个计算属性来判断是否有操作权限
const hasOperationPermission = (record: API.UserInTeamVo) => {
  return canEdit(record) || canKick(record) || canDelete(record)
}

// 获取变动类型颜色
const getChangeTypeColor = (type: number) => {
  const colorMap: Record<number, string> = {
    0: 'blue', // 申请
    1: 'green', // 邀请
    2: 'purple', // 创建
    3: 'orange' // 离开
  }
  return colorMap[type] || 'gray'
}

// 获取变动类型文本
const getChangeTypeText = (type: number) => {
  const textMap: Record<number, string> = {
    0: '申请加入',
    1: '邀请加入',
    2: '创建团队',
    3: '成员离开'
  }
  return textMap[type] || '未知'
}

// 获取状态颜色
const getStatusColor = (record: API.TeamUserHistoryVo) => {
  if (record.status === 1) return 'orange' // 未处理
  if (record.result === 1) return 'green' // 已通过
  if (record.result === 0) return 'red' // 已拒绝
  return 'blue' // 其他情况（如离开记录）
}

// 获取状态文本
const getStatusText = (record: API.TeamUserHistoryVo) => {
  if (record.status === 0) return '已处理'
  if (record.status === 1) return '待处理'
  if (record.result === 1) return '已通过'
  if (record.result === 0) return '已拒绝'
  if (record.type === 3) return '已离开' // 离开记录
  return '已处理'
}

// 添加变动记录显示控制
const isChangeLogVisible = ref(false)

// 切换变动记录显示状态
const toggleChangeLog = () => {
  isChangeLogVisible.value = !isChangeLogVisible.value
  // 如果展开且没有数据，则加载数据
  if (isChangeLogVisible.value && teamUserHistoryVoList.value.length === 0) {
    loadTeamMemberChangeLogs()
  }
}

// 处理申请通过
const handleApprove = async (record: API.TeamUserHistoryVo) => {
  // TODO: 实现申请通过逻辑
}

// 处理申请拒绝
const handleReject = async (record: API.TeamUserHistoryVo) => {
  // TODO: 实现申请拒绝逻辑
}

onMounted(async () => {
  await loadTeamUserList()
})
</script>

<template>
  <div class="team-manage">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <!-- 左侧搜索区域 -->
      <div class="search-section">
        <div class="search-inputs">
          <Input v-model="searchForm.name" placeholder="请输入姓名" allow-clear>
            <template #prefix>
              <icon-user />
            </template>
          </Input>
          <Input v-model="searchForm.email" placeholder="请输入邮箱" allow-clear>
            <template #prefix>
              <icon-email />
            </template>
          </Input>
          <Input v-model="searchForm.phone" placeholder="请输入手机号" allow-clear>
            <template #prefix>
              <icon-phone />
            </template>
          </Input>
          <Select v-model="searchForm.role" :options="roleOptions" :default-value="-1" />
        </div>
        <div class="search-buttons">
          <Button type="primary" @click="handleSearch">
            <template #icon>
              <icon-search />
            </template>
            搜索
          </Button>
          <Button @click="handleReset">
            <template #icon>
              <icon-refresh />
            </template>
            重置
          </Button>
        </div>
      </div>

      <!-- 右侧操作区域 -->
      <div class="action-section">
        <Button v-if="isTeamOwner" type="primary" @click="handleEditTeam">
          <template #icon>
            <icon-edit />
          </template>
          编辑团队
        </Button>
        <Button v-if="isTeamOwner" type="primary" @click="handleInvite">
          <template #icon>
            <icon-plus />
          </template>
          邀请加入
        </Button>
        <Button v-if="isTeamOwner" type="primary" status="success" @click="handleCreateUser">
          <template #icon>
            <icon-user-add />
          </template>
          创建用户
        </Button>
        <div class="team-count-board">
          <Tooltip content="团队人数">
            <div class="count-wrapper">
              <IconUserGroup class="team-icon" />
              <span class="count-text">
                <span>{{ formData.length }}</span>
                /
                <span>{{ teamStore.selectedTeam?.maxMember || '-' }}</span>
              </span>
            </div>
          </Tooltip>
        </div>
      </div>
    </div>

    <!-- 添加邀请弹窗 -->
    <Modal v-model:visible="inviteVisible" title="邀请成员" :width="840">
      <div class="invite-container">
        <div class="invite-box">
          <div class="invite-title invite-title-search">搜索用户名邀请</div>
          <div class="invite-content">
            <div class="search-invite-container">
              <Select
                v-model="selectedUserIds"
                :style="{ width: '320px' }"
                multiple
                allow-search
                allow-clear
                :options="getFilteredUsers"
                :max-tag-count="2"
                :limit="5"
                :loading="loading"
                :popup-max-height="300"
                placeholder="请输入用户名搜索"
                @search="handleSearchUser"
                @change="handleSelectionChange"
                @focus="handleFocus"
                @popup-visible-change="handleDropdownVisibleChange"
                @dropdown-reach-bottom="handleReachBottom"
              >
                <template #empty>
                  <div class="empty-text">{{ emptyText }}</div>
                </template>
                <template #option="{ data }">
                  <Space align="center">
                    <Avatar :size="24" :image-url="data.avatar">
                      {{ data.nickname?.[0] || data.label[0] }}
                    </Avatar>
                    <span
                      :class="{
                        'team-member': data.isInTeam,
                        'pending-invite': data.isPending
                      }"
                    >
                      {{ data.label }}
                      <span v-if="data.isInTeam" class="status-tag team-tag">已在团队中</span>
                      <span v-if="data.isPending" class="status-tag pending-tag">待确认邀请</span>
                    </span>
                  </Space>
                </template>
                <template #label="{ data }">
                  <Space align="center">
                    <Avatar :size="24" :image-url="data.avatar">
                      {{ data.nickname?.[0] || data.label[0] }}
                    </Avatar>
                    {{ data.label }}
                  </Space>
                </template>
              </Select>
              <Button
                type="primary"
                :disabled="selectedUsers.length === 0"
                @click="handleInviteUsers"
                :style="{ width: '100px' }"
              >
                邀请
              </Button>
            </div>
            <div class="selected-users" v-if="selectedUsers.length > 0">
              <div class="selected-count">已选择用户（{{ selectedUsers.length }}/5）：</div>
              <div class="selected-tags">
                <Tag
                  v-for="user in selectedUsers"
                  :key="user.value"
                  closable
                  @close="handleRemoveUser(user.value)"
                >
                  <Space align="center">
                    <Avatar :size="24" :image-url="user.avatar">
                      {{ user.nickname?.[0] || user.label[0] }}
                    </Avatar>
                    {{ user.label }}
                  </Space>
                </Tag>
              </div>
            </div>
          </div>
        </div>
        <div class="invite-box">
          <div class="invite-title invite-title-link">分享链接邀请</div>
          <div class="invite-content">
            <div class="generate-link-section">
              <Button type="primary" status="success" long @click="handleGenerateLink">
                <template #icon><icon-link /></template>
                生成邀请码
              </Button>
            </div>

            <div v-if="inviteLink" class="link-display-section">
              <!-- 短链接代码 -->
              <div class="link-box">
                <Input v-model="inviteCode" readonly :style="{ width: '100%' }">
                  <template #prefix>
                    <span class="link-prefix">邀请码：</span>
                  </template>
                  <template #suffix>
                    <Button type="text" size="mini" @click="() => handleCopyLink('code')">
                      <template #icon><icon-copy /></template>
                      复制
                    </Button>
                  </template>
                </Input>
              </div>

              <!-- 完整URL -->
              <div class="link-box">
                <Input v-model="inviteLink" readonly :style="{ width: '100%' }">
                  <template #prefix>
                    <span class="link-prefix">邀请链接：</span>
                  </template>
                  <template #suffix>
                    <Button type="text" size="mini" @click="() => handleCopyLink('url')">
                      <template #icon><icon-copy /></template>
                      复制
                    </Button>
                  </template>
                </Input>
              </div>

              <div class="link-info">邀请码有效期：30分钟</div>
            </div>
          </div>
        </div>
      </div>
    </Modal>

    <!-- 修改表格布局容器 -->
    <div class="tables-container">
      <!-- 成员表卡片 -->
      <div class="table-card member-table-card">
        <Table
          :data="formData"
          :pagination="false"
          :scroll="{ x: 1080, y: 'calc(100vh - 180px)' }"
          class="member-table"
        >
          <template #columns>
            <TableColumn title="头像" align="center" :width="88">
              <template #cell="{ record }">
                <Avatar :size="32" :image-url="record.avatar">
                  {{ record.nickname?.[0] || record.username?.[0] }}
                </Avatar>
              </template>
            </TableColumn>
            <TableColumn title="用户名" data-index="username" :width="100" />
            <TableColumn title="姓名" data-index="name" :width="100" />
            <TableColumn title="昵称" data-index="nickname" :width="100" />
            <TableColumn title="角色" align="left" :width="100">
              <template #cell="{ record }">
                <Tag :color="getRoleInfo(record).color">
                  {{ getRoleInfo(record).text }}
                </Tag>
              </template>
            </TableColumn>
            <TableColumn title="标签" align="center" :width="120">
              <template #cell="{ record }">
                <Space wrap>
                  <Tag
                    v-for="(tag, index) in record.tags"
                    :key="tag"
                    :color="getTagColor(tag, index)"
                    size="small"
                  >
                    {{ tag }}
                  </Tag>
                  <Tag v-if="!record.tags?.length" size="small" color="gray"> 暂无标签 </Tag>
                </Space>
              </template>
            </TableColumn>
            <TableColumn title="邮箱" data-index="email" :width="180" />
            <TableColumn title="手机号" data-index="phone" :width="120" />
            <TableColumn title="加入时间" align="left" :width="140">
              <template #cell="{ record }">
                {{ dayjs(record.createAt).format('YYYY-MM-DD HH:mm') }}
              </template>
            </TableColumn>
            <TableColumn title="操作" align="center" :width="260" fixed="right">
              <template #cell="{ record }">
                <Space v-if="hasOperationPermission(record)">
                  <Button
                    v-if="canEdit(record)"
                    type="text"
                    size="small"
                    @click="handleEdit(record)"
                  >
                    编辑
                  </Button>
                  <Button
                    v-if="canKick(record)"
                    type="text"
                    size="small"
                    status="warning"
                    @click="handleKick(record)"
                  >
                    <template #icon><icon-export /></template>
                    踢出
                  </Button>
                  <Button
                    v-if="canDelete(record)"
                    type="text"
                    size="small"
                    status="danger"
                    @click="handleDelete(record)"
                  >
                    <template #icon><icon-delete /></template>
                    删除
                  </Button>
                </Space>
                <span v-else class="no-permission">无权限</span>
              </template>
            </TableColumn>
          </template>
        </Table>
      </div>

      <!-- 变动记录卡片 -->
      <div class="table-card change-log-card" :class="{ 'is-collapsed': !isChangeLogVisible }">
        <!-- 添加展开/收起按钮 -->
        <div class="card-header">
          <div class="header-content">
            <span class="header-title">变动记录</span>
            <Button type="text" class="collapse-button" @click="toggleChangeLog">
              <template #icon>
                <icon-right :style="{ transform: isChangeLogVisible ? 'rotate(90deg)' : 'none' }" />
              </template>
              {{ isChangeLogVisible ? '收起' : '展开' }}
            </Button>
          </div>
        </div>

        <!-- 变动记录表格 -->
        <div class="card-content" v-show="isChangeLogVisible">
          <Table
            :data="teamUserHistoryVoList"
            :pagination="false"
            :scroll="{ y: 'calc(100vh - 240px)' }"
            class="change-log-table"
          >
            <template #columns>
              <TableColumn title="变动类型" align="center" :width="100">
                <template #cell="{ record }">
                  <Tag :color="getChangeTypeColor(record.type)">
                    {{ getChangeTypeText(record.type) }}
                  </Tag>
                </template>
              </TableColumn>

              <!-- 根据不同类型显示不同的操作人 -->
              <TableColumn title="相关成员" align="left" :width="200">
                <template #cell="{ record }">
                  <div class="record-users">
                    <!-- 邀请记录 -->
                    <template v-if="record.type === 1">
                      <div class="user-action">
                        <div class="user-info">
                          <a-avatar :size="24" :image-url="record.inviter?.avatar">
                            {{ record.inviter?.username?.[0]?.toUpperCase() }}
                          </a-avatar>
                          <span>{{ record.inviter?.username }}</span>
                        </div>
                        <icon-right class="action-arrow" />
                        <div class="user-info">
                          <a-avatar :size="24" :image-url="record.invited?.avatar">
                            {{ record.invited?.username?.[0]?.toUpperCase() }}
                          </a-avatar>
                          <span>{{ record.invited?.username }}</span>
                        </div>
                      </div>
                    </template>

                    <!-- 离开记录 -->
                    <template v-else-if="record.type === 3">
                      <div class="user-info">
                        <a-avatar :size="24" :image-url="record.remover?.avatar">
                          {{ record.remover?.username?.[0]?.toUpperCase() }}
                        </a-avatar>
                        <span>{{ record.remover?.username }}</span>
                      </div>
                    </template>

                    <!-- 申请记录 -->
                    <template v-else-if="record.type === 0">
                      <div class="user-info">
                        <a-avatar :size="24" :image-url="record.applicant?.avatar">
                          {{ record.applicant?.username?.[0]?.toUpperCase() }}
                        </a-avatar>
                        <span>{{ record.applicant?.username }}</span>
                      </div>
                    </template>
                  </div>
                </template>
              </TableColumn>

              <TableColumn title="处理状态" align="center" :width="120">
                <template #cell="{ record }">
                  <div class="status-wrapper">
                    <Tag :color="getStatusColor(record)">
                      {{ getStatusText(record) }}
                    </Tag>
                    <!-- 仅对未处理的申请显示处理按钮 -->
                    <div v-if="record.type === 0 && record.status === 1" class="action-buttons">
                      <a-button
                        type="text"
                        size="mini"
                        status="success"
                        @click="handleApprove(record)"
                      >
                        <template #icon><icon-check /></template>
                        通过
                      </a-button>
                      <a-button
                        type="text"
                        size="mini"
                        status="danger"
                        @click="handleReject(record)"
                      >
                        <template #icon><icon-close /></template>
                        拒绝
                      </a-button>
                    </div>
                  </div>
                </template>
              </TableColumn>

              <TableColumn title="操作人" align="left" :width="120">
                <template #cell="{ record }">
                  <div class="user-info">
                    <a-avatar :size="24" :image-url="record.creator?.avatar">
                      {{ record.creator?.username?.[0]?.toUpperCase() }}
                    </a-avatar>
                    <span>{{ record.creator?.username }}</span>
                  </div>
                </template>
              </TableColumn>

              <TableColumn title="处理时间" align="center" :width="160">
                <template #cell="{ record }">
                  <div class="time-info">
                    <div>{{ dayjs(record.updateAt).format('YYYY-MM-DD HH:mm') }}</div>
                  
                  </div>
                </template>
              </TableColumn>
            </template>
          </Table>
        </div>
      </div>
    </div>

    <!-- 修改编辑弹窗 -->
    <Modal v-model:visible="editVisible" title="编辑用户" @cancel="handleEditCancel" :width="500">
      <Form ref="editUserFormRef" :model="editUserForm" :rules="editUserRules">
        <FormItem field="nickname" label="昵称">
          <Input v-model="editUserForm.nickname" placeholder="请输入昵称（1-32位）" allow-clear />
        </FormItem>

        <FormItem field="password" label="密码">
          <Input
            v-model="editUserForm.password"
            type="password"
            placeholder="请输入密码（8-32位）"
            allow-clear
          />
        </FormItem>
      </Form>
      <template #footer>
        <Space>
          <Button @click="handleEditCancel">取消</Button>
          <Button type="primary" @click="handleEditSubmit">确定</Button>
        </Space>
      </template>
    </Modal>

    <!-- 在 template 最后添加创建用户弹窗 -->
    <Modal
      v-model:visible="createUserVisible"
      title="创建用户"
      @cancel="handleCreateUserCancel"
      :width="500"
    >
      <Form ref="createUserFormRef" :model="createUserForm" :rules="createUserRules">
        <FormItem field="username" label="用户名" required>
          <Input
            v-model="createUserForm.username"
            placeholder="请输入用户名（6-32位）"
            allow-clear
          />
        </FormItem>

        <FormItem field="name" label="姓名" required>
          <Input v-model="createUserForm.name" placeholder="请输入姓名（1-10位）" allow-clear />
        </FormItem>
      </Form>
      <template #footer>
        <Space>
          <Button @click="handleCreateUserCancel">取消</Button>
          <Button type="primary" @click="handleCreateUserSubmit">确定</Button>
        </Space>
      </template>
    </Modal>

    <!-- 修改团队信息弹窗 -->
    <Modal
      v-model:visible="editTeamVisible"
      title="编辑团队信息"
      @cancel="editTeamVisible = false"
      :width="500"
    >
      <Form ref="editTeamFormRef" :model="editTeamForm" :rules="editTeamRules">
        <FormItem field="name" label="团队名称" required>
          <Input v-model="editTeamForm.name" placeholder="请输入团队名称" allow-clear />
        </FormItem>

        <FormItem field="description" label="团队简介">
          <Textarea
            v-model="editTeamForm.description"
            placeholder="请输入团队简介"
            :max-length="300"
            show-word-limit
            allow-clear
          />
        </FormItem>

        <FormItem field="maxMember" label="人数上限" required>
          <Select
            v-model="editTeamForm.maxMember"
            :options="memberLimitOptions"
            placeholder="请选择团队人数上限"
          >
            <template #extra>
              <div class="member-limit-tip">当前团队人数：{{ formData.length }}人</div>
            </template>
          </Select>
        </FormItem>
      </Form>
      <template #footer>
        <Space>
          <Button @click="editTeamVisible = false">取消</Button>
          <Button type="primary" @click="handleEditTeamSubmit">确定</Button>
        </Space>
      </template>
    </Modal>
  </div>
</template>

<style scoped>
.team-manage {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
  padding: 16px;
  background: var(--color-bg-2);
  border-radius: 4px;
}

.search-section {
  flex: 1;
  min-width: 300px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.search-inputs {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.search-inputs > * {
  width: 200px;
  min-width: 160px;
  flex: 1;
}

.search-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-section {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: flex-start;
}

.member-table {
  flex: 1;
  background: var(--color-bg-2);
  border-radius: 4px;
  height: calc(100vh - 180px); /* 视窗高度减去头部和边距 */
}

.user-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.username {
  font-size: 14px;
  font-weight: 500;
  color: var(--color-text-1);
}

.nickname {
  font-size: 12px;
  color: var(--color-text-3);
}

.invite-container {
  display: flex;
  gap: 20px;
  height: 320px;
}

.invite-box {
  flex: 1;
  width: 50%;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  padding: 16px;
  height: 300px;
  min-width: 0;
}

.invite-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  text-align: center;
  padding: 8px 0;
  border-radius: 4px;
}

.invite-title-search {
  background-color: var(--color-primary-light-1);
  color: var(--color-primary);
}

.invite-title-link {
  background-color: var(--color-success-light-1);
  color: var(--color-success);
}

.invite-content {
  height: calc(100% - 50px);
  overflow-y: auto;
}

.search-invite-container {
  display: flex;
  gap: 12px;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.selected-users {
  margin-top: 16px;
  padding: 0 12px;
}

.selected-count {
  color: var(--color-text-2);
  font-size: 14px;
  margin-bottom: 8px;
}

.loading-text {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--color-text-3);
  font-size: 14px;
}

.empty-text {
  color: var(--color-text-3);
  text-align: center;
  padding: 8px 0;
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

:deep(.arco-icon-loading) {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.loading-more,
.no-more {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  background: var(--color-bg-2);
  text-align: center;
  padding: 8px 0;
  margin: 0;
  color: var(--color-text-3);
  font-size: 12px;
  border-top: 1px solid var(--color-border);
  z-index: 1;
}

.loading-more {
  cursor: pointer;
}

:deep(.arco-select-dropdown) {
  padding: 0 !important;
}

:deep(.arco-select-dropdown-list) {
  padding: 4px 0;
}

:deep(.arco-select-dropdown-list-wrapper) {
  padding-bottom: 32px;
}

:deep(.arco-select-option) {
  padding: 4px 12px !important;
}

:deep(.arco-avatar) {
  background-color: var(--color-primary-light-4);
  color: var(--color-primary-6);
}

:deep(.arco-select-view-tag) {
  max-width: 120px;
}

.virtual-list-container {
  max-height: 150px;
  overflow-y: auto;
  padding: 4px 0;
}

.virtual-list-item {
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.virtual-list-item:hover {
  background-color: var(--color-fill-2);
}

.loading-more {
  text-align: center;
  padding: 8px 0;
  color: var(--color-text-3);
  font-size: 12px;
  background: var(--color-bg-2);
}

.team-member {
  color: var(--color-text-3);
}

.pending-invite {
  color: var(--color-text-3);
}

.status-tag {
  font-size: 12px;
  padding: 0 6px;
  border-radius: 10px;
  line-height: 18px;
  margin-left: 8px;
}

.team-tag {
  background-color: var(--color-fill-2);
  color: var(--color-text-3);
}

.pending-tag {
  background-color: var(--color-warning-light-1);
  color: var(--color-warning-dark-2);
}

:deep(.arco-select-option-disabled) {
  .team-member,
  .pending-invite {
    cursor: not-allowed;
  }
}

/* 修改团队人数看板样式 */
.team-count-board {
  display: flex;
  align-items: center;
  padding: 0 16px;
  height: 32px;
  background: linear-gradient(45deg, var(--color-primary-light-4), var(--color-success-light-4));
  border-radius: 16px;
  gap: 8px;
  box-shadow: 0 2px 6px rgba(var(--primary-6), 0.1);
  transition: all 0.3s ease;
  cursor: help; /* 添加提示性鼠标样式 */
}

.team-count-board:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(var(--primary-6), 0.15);
}

.team-icon {
  font-size: 16px;
  color: var(--color-primary-6);
  transition: transform 0.3s ease;
}

.team-count-board:hover .team-icon {
  transform: scale(1.1);
}

.count-text {
  font-size: 14px;
  color: var(--color-text-1);
  font-weight: 600;
  letter-spacing: 0.5px;
}

/* 添加数字高亮效果 */
.count-text span {
  color: var(--color-primary-6);
  margin: 0 2px;
}

/* 添加包装器样式 */
.count-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 添加警告弹窗样式 */
:deep(.warning-modal) {
  .arco-modal-header {
    border-bottom: none;
    padding-bottom: 0;
  }

  .arco-modal-title {
    color: rgb(var(--warning-6));
    font-size: 16px;
    text-align: center;
  }

  .arco-modal-content {
    text-align: center;
    font-size: 14px;
    color: var(--color-text-2);
    padding: 24px;
  }

  .arco-modal-footer {
    border-top: none;
    padding-top: 0;
  }
}

.generate-link-section {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.link-display-section {
  padding: 0 20px;
}

.link-box {
  margin-bottom: 12px;
}

.link-box:last-of-type {
  margin-bottom: 16px;
}

:deep(.arco-input-wrapper) {
  background-color: var(--color-fill-2);
}

:deep(.arco-input[readonly]) {
  cursor: text;
  color: var(--color-text-2);
}

.link-prefix {
  color: var(--color-text-3);
  font-size: 14px;
  margin-right: 4px;
}

.member-limit-tip {
  font-size: 12px;
  color: var(--color-text-3);
  padding: 4px 12px;
}

/* 调整按钮和输入框的基础样式 */
:deep(.arco-btn) {
  white-space: nowrap;
}

:deep(.arco-input-wrapper),
:deep(.arco-select) {
  width: 100%;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .search-section {
    width: 100%;
  }

  .action-section {
    width: 100%;
    justify-content: flex-end;
  }
}

@media screen and (max-width: 768px) {
  .search-inputs > * {
    width: 100%;
  }

  .action-section {
    justify-content: flex-start;
  }
}

/* 添加无权限样式 */
.no-permission {
  color: var(--color-text-3);
  font-size: 13px;
}

/* 修改表格布局容器样式 */
.tables-container {
  display: flex;
  gap: 0;
  margin-top: 16px;
  position: relative;
  height: calc(100vh - 180px);
  overflow: hidden;
}

/* 表格卡片通用样式 */
.table-card {
  background: var(--color-bg-2);
  border-radius: 4px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

/* 成员表卡片样式 */
.member-table-card {
  flex: 3; /* 占比7份 */
  transition: all 0.3s ease;
  margin-right: 16px;
  min-width: 0; /* 允许收缩 */
}

/* 变动记录卡片样式 */
.change-log-card {
  flex: 7; /* 占比3份 */
  min-width: 480px; /* 最小宽度 */
  max-width: 50%; /* 最大不超过容器的30% */
  transition: all 0.3s ease;
  border-left: 1px solid var(--color-border);
  display: flex;
  flex-direction: column;
}

/* 折叠状态样式 */
.change-log-card.is-collapsed {
  flex: 0;
  min-width: 48px; /* 收起时的宽度 */
  width: 48px;
}

/* 卡片头部样式 */
.card-header {
  padding: 12px;
  border-bottom: 1px solid var(--color-border);
  background: var(--color-bg-2);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 折叠状态下的头部样式 */
.is-collapsed .card-header {
  writing-mode: vertical-lr;
  text-orientation: mixed;
  height: 100%;
  padding: 16px 8px;
  justify-content: flex-start;
}

/* 标题样式 */
.header-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--color-text-1);
  transition: all 0.3s ease;
}

/* 折叠状态下的标题样式 */
.is-collapsed .header-title {
  margin-bottom: 16px;
}

/* 折叠按钮样式 */
.collapse-button {
  padding: 4px;
  transition: all 0.3s ease;
}

/* 折叠状态下的按钮样式 */
.is-collapsed .collapse-button {
  writing-mode: horizontal-tb;
}

/* 内容区域样式 */
.card-content {
  flex: 1;
  overflow: hidden;
  opacity: 1;
  transition: opacity 0.3s ease;
}

/* 折叠状态下隐藏内容 */
.is-collapsed .card-content {
  display: none;
}

/* 表格样式 */
.change-log-table {
  height: 100%;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 调整展开按钮容器样式 */
.collapse-button-container {
  position: absolute; /* 使用绝对定位 */
  right: -40px; /* 调整按钮位置 */
  top: 50%;
  transform: translateY(-50%);
}

.record-users {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-action {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-arrow {
  color: var(--color-text-3);
  font-size: 14px;
}

.status-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  margin-top: 4px;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.create-time {
  font-size: 12px;
  color: var(--color-text-3);
}
</style>
